package org.laizili.solution.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/reorder-data-in-log-files/">937. 重新排列日志文件</a>
 * <p>
 * tags: 自定义关键字排序; 稳定排序
 */
public class Problem937 {
    private static class Solution {
        public String[] reorderLogFiles(String[] logs) {
            Map<String, String[]> cache = new HashMap<>();
            for (String log : logs) {
                // 分割成两段: identifier log_content
                cache.put(log, log.split(" ", 2));
            }
            // Arrays.sort(T[], comparator) 是稳定排序
            Arrays.sort(logs, (log1, log2) -> {
                String[] log1Splits = cache.get(log1);
                String[] log2Splits = cache.get(log2);
                boolean isLetterLog1 = Character.isLowerCase(log1Splits[1].charAt(0));
                boolean isLetterLog2 = Character.isLowerCase(log2Splits[1].charAt(0));
                if (isLetterLog1 && isLetterLog2) {
                    int cmpRes = log1Splits[1].compareTo(log2Splits[1]);
                    if (cmpRes == 0) {
                        return log1Splits[0].compareTo(log2Splits[0]);
                    } else return cmpRes;
                } else if (isLetterLog1) {
                    // log1 是 letter log
                    return -1;
                } else if (isLetterLog2) {
                    // log2 是 letter log
                    return 1;
                } else {
                    // 都不是letter log
                    return 0;
                }
            });
            return logs;
        }
    }
}
